package com.lanjiu.lib.communication.dispatcher;

import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.event.OnEventListener;

import io.netty.channel.Channel;

/**
 * @description: 消息转发器，负责将接收到的消息转发到应用层
 * @author: Panwei
 * @date: 2019/10/28 14:30
 */
public class MsgDispatcher {

    private OnEventListener mOnEventListener;

    public MsgDispatcher() {

    }

    public void setOnEventListener(OnEventListener listener) {
        this.mOnEventListener = listener;
    }

    public BusinessProtocolMessageStandard.UnifiedEntranceMessage beforeDispatchMsg(Channel channel, BusinessProtocolMessageStandard.UnifiedEntranceMessage msg) {
        if (mOnEventListener != null) {
            return mOnEventListener.beforeDispatchMsg(channel, msg);
        }
        return msg;
    }

    /**
     * 接收消息，并通过OnEventListener转发消息到应用层
     *
     * @param msg
     */
    public void receivedMsg(BusinessProtocolMessageStandard.UnifiedEntranceMessage msg) {
        if (mOnEventListener == null) {
            return;
        }
        mOnEventListener.dispatchMsg(msg);
    }

    public void dispatchFailureMsg(BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg, int failureMsgContentType) {
        BusinessProtocolMessageStandard.UnifiedEntranceMessage networkError = msg.getUnifiedEntranceMessage();
        BusinessProtocolMessageStandard.Head head = BusinessProtocolMessageStandard.Head.newBuilder(networkError.getHead()).setStatusReport(IMSConfig.STATUS_REPORT_FAILURE).setMsgContentType(failureMsgContentType).build();
        BusinessProtocolMessageStandard.UnifiedEntranceMessage unified = BusinessProtocolMessageStandard.UnifiedEntranceMessage.newBuilder(networkError).setHead(head).build();
        receivedMsg(unified);
    }
}
